<?php


namespace app\api\controller;


use app\common\controller\Api;
use app\api\model\Users as UsersModel;
use app\common\library\Sms;
use think\Validate;
use tencentcloud\TLSSigAPIv2;

class Users extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }


    /**
     * 获取用户openid
     */
    public function openid()
    {
        $code = $this->request->param('code');
        if (!$code) {
            $this->error('缺少code');
        }

        $appId = config('site.appid');
        $appSecret = config('site.app_secret');

        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appId&secret=$appSecret&js_code=$code&grant_type=authorization_code";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        $data = curl_exec($curl);
        curl_close($curl);
        $response = json_decode($data, true);

        $this->success('获取成功', ['openid' => $response['openid']]);
    }


    /**
     * 获取用户信息
     */
    public function getUserInfo()
    {
        $openid = $this->request->post('openid');
        $sign = $this->request->post('sign');

        if (!$openid || !$sign) {
            $this->error(__('Invalid parameters'));
        }
        $des = new Tdes();
        $key = $des->encrypt('11e9fe51d9d4d1f4d80bf77bd31bc3d3', '11e9fe51d9d4d1f4d80bf77bd31bc3d3');
        if (trim($sign) !== trim($key)) {
            $this->error('签名错误');
        }

        $ret = $this->auth->userLogin($openid);
        if ($ret) {
            $userInfo = $this->auth->getUserinfo();

            switch ($userInfo['type']) {
                case 0:
//                    if (strpos($userInfo['avatar'], 'https://') == false) {
//                        $userInfo['avatar'] = imgUrl($userInfo['avatar']);
//                    }

                    if ($userInfo['is_vip'] == 1 && $userInfo['expire_time'] > time()) {
                        if ($userInfo['expire_time'] > 0 && $userInfo['expire_time'] > time()) {
                            $userInfo['expire_time'] = ceil(($userInfo['expire_time'] - time()) / 86400);
                        }
                    } else {
                        $userInfo['is_vip'] = 0;
                        $userInfo['expire_time'] = 0;
                    }
                    $userInfo['collection_num'] = db('collection')->where('user_id', $userInfo['id'])->count();
                    $userInfo['goutong'] = db('order')->where(['user_id' => $userInfo['id'], 'type' => 3, 'is_pay' => 1])->count();
                    if (strpos($userInfo['avatar'], 'https://') === false) {
                        $avatar = imgUrl($userInfo['avatar']);
                    } else {
                        $avatar = $userInfo['avatar'];
                    }
                    $this->updateImUserInfo($userInfo['im'], $userInfo['nickname'], $avatar);
                    break;
                case 1:
                    $info = db('lawyer_info')->field('introduction,name as nickname,avatar')->where('user_id', $userInfo['id'])->where('status', '1')->find();

                    if (strpos($info['avatar'], 'https://') === false) {
                        $avatar = imgUrl($info['avatar']);
                    } else {
                        $avatar = $info['avatar'];
                    }
                    $this->updateImUserInfo($userInfo['im'], $info['nickname'], $avatar);

                    $userInfo = array_merge($userInfo, $info);
                    break;
                case 3:
                    $info = db('company_info')->field('name as nickname,avatar')->where('user_id', $userInfo['id'])->where('status', '1')->find();
                    $userInfo = array_merge($userInfo, $info);
                    break;
            }

            if (strpos($userInfo['avatar'], 'https://') === false) {
                $userInfo['avatar'] = imgUrl($userInfo['avatar']);
            }

            // 已提现金额
            $withdraw = db('withdraw')->where('status', '3')->where('user_id', $userInfo['id'])->sum('money');
            $userInfo['withdraw_money'] = $withdraw;

            // 聊天密钥
            $userInfo['user_sig'] = $this->getUserSig($userInfo['im']);

            // 用户是否已关注公众号
            if ($userInfo['mp_openid']) {
                $userInfo['is_subscribe'] = $this->isSubscribe($userInfo['mp_openid']);
            } else {
                $userInfo['is_subscribe'] = 0;
            }

            if (!$userInfo['mp_openid']) {
                $userInfo['mp_openid'] = "";
            }


            if (empty($userInfo['qrcode'])) {
                // $instance = new Qrcode();
                // $instance->invitation1($userInfo['id']);
            }

            $this->success('获取成功', $userInfo);
        } else {
            $this->error($this->auth->getError());
        }
    }


    /**
     * 修改用户信息
     */
    public function updateUserInfo()
    {
        $post = $this->request->post();

        if (!$post['avatar'] || !$post['nickname'] || !$post['sign']) {
            $this->error('缺少参数');
        }

        $des = new Tdes();
        $key = $des->encrypt('11e9fe51d9d4d1f4d80bf77bd31bc3d3', '11e9fe51d9d4d1f4d80bf77bd31bc3d3');
        if (trim($post['sign']) !== trim($key)) {
            $this->error('签名错误');
        }


        $im = db('user')->where('id', $this->auth->id)->value('im');
        $this->updateImUserInfo($im, $post['nickname'], $post['avatar']);

        if (strpos($post['avatar'], 'https://') === false) {
//            var_dump(111);exit;
            $avatar = explode('com', $post['avatar']);
            $post['avatar'] = $avatar[1];
        }

        $m = new UsersModel();
        $m->allowField(true)->isUpdate()->save($post, ['id' => $this->auth->id]);
        $this->success('修改成功');
    }

    /**
     * 更新用户im信息
     *
     * @param string $im 聊天账号
     * @param string $nickname 用户昵称
     * @param string $avatar 用户头像
     */
    public function updateImUserInfo($im, $nickname, $avatar)
    {
        $userInfo = [
            'From_Account' => $im,
            "ProfileItem" => [
                ["Tag" => "Tag_Profile_IM_Nick", "Value" => $nickname],
                ["Tag" => "Tag_Profile_IM_Image", "Value" => $avatar]
            ]
        ];

        $data = json_encode($userInfo);
//        var_dump($data);exit;

        $sdkappid = config('site.sdkappid');
        // 生成用户聊天账号密钥
        $userSig = $this->getUserSig('administrator');
        $url = "https://console.tim.qq.com/v4/profile/portrait_set?sdkappid={$sdkappid}&identifier=administrator&usersig=$userSig&random=99999999&contenttype=json";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: text'));
        $result = curl_exec($ch);
        curl_close($ch);
        return json_decode($result, true);
    }


    /**
     * 注册会员
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email 邮箱
     * @param string $mobile 手机号
     * @param string $code 验证码
     */
    public function register()
    {
        $nickname = $this->request->post('nickname');
        $avatar = $this->request->post('avatar');
        $openid = $this->request->post('openid');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        $invitation_code = $this->request->post('invitation_code', '');
        if (!$nickname) {
            $this->error('昵称获取失败');
        }
        if (!$avatar) {
            $this->error('头像获取失败');
        }
        if (!$openid) {
            $this->error('openid获取失败');
        }
        if (!$mobile) {
            $this->error('请输入手机号码');
        }
        if (!$code) {
            $this->error('请输入短信验证码');
        }
//        if (!$nickname || !$avatar || !$openid || !$mobile || !$code) {
//            $this->error(__('Invalid parameters'));
//        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error('手机号码格式错误');
        }
        $ret = Sms::check($mobile, $code, 'register');
//        var_dump($ret);exit;
        if (!$ret) {
            $this->error('验证码不正确');
        }
        $ret = $this->auth->registerAndLogin($openid, $nickname, $avatar, $mobile, $invitation_code, []);
        if ($ret) {
//            db('invitation_code')->where('code', $invitation_code)->setField('status', 1);
            $userInfo = $this->auth->getUserinfo();

            // 注册聊天账号
            $registerIm = $this->registerIm($userInfo['im'], $userInfo['nickname'], $userInfo['avatar']);
            if ($registerIm['ActionStatus'] != "OK") {
                $this->error('聊天账号注册失败');
            }

            switch ($userInfo['type']) {
                case 0:
                    if ($userInfo['is_vip'] == 1 && $userInfo['expire_time'] > time()) {
                        if ($userInfo['expire_time'] > 0) {
                            $userInfo['expire_time'] = ceil(($userInfo['expire_time'] - time()) / 86400);
                        }
                    } else {
                        $userInfo['expire_time'] = 0;
                        $userInfo['is_vip'] = 0;
                    }
                    $userInfo['collection_num'] = db('collection')->where('user_id', $userInfo['id'])->count();
                    $userInfo['goutong'] = db('order')->where(['user_id' => $userInfo['id'], 'type' => 3, 'is_pay' => 1])->count();
                    break;
                case 1:
                    $info = db('lawyer_info')->field('introduction,name as nickname,avatar')->where('user_id', $userInfo['id'])->where('status', '1')->find();
                    $userInfo = array_merge($userInfo, $info);
                    break;
//                case 2:
//                    $info = db('partner')->field('name as nickname,avatar')->where('user_id', $userInfo['id'])->find();
//                    $userInfo = array_merge($userInfo, $info);
//                    break;
                case 3:
                    $info = db('company_info')->field('name as nickname,avatar')->where('user_id', $userInfo['id'])->where('status', '1')->find();
                    $userInfo = array_merge($userInfo, $info);
                    break;
            }

            if (strpos($userInfo['avatar'], 'https://wx.qlogo.cn/') === false) {
                $userInfo['avatar'] = imgUrl($userInfo['avatar']);
            }

            // 已提现金额
            $withdraw = db('withdraw')->where('status', '3')->where('user_id', $userInfo['id'])->sum('money');
            $userInfo['withdraw_money'] = $withdraw;
            // 聊天密钥
            $userInfo['user_sig'] = $this->getUserSig($userInfo['im']);

            // 用户是否已关注公众号
            if ($userInfo['mp_openid']) {
                $userInfo['is_subscribe'] = $this->isSubscribe($userInfo['mp_openid']);
            } else {
                $userInfo['is_subscribe'] = 0;
            }

            if (!$userInfo['mp_openid']) {
                $userInfo['mp_openid'] = "";
            }

            if (empty($userInfo['qrcode'])) {
                // $instance = new Qrcode();
                // $instance->invitation1($userInfo['id']);
            }

            $this->success('注册成功', $userInfo);
        } else {
            $this->error($this->auth->getError());
        }
    }


    public function register1()
    {
        $openid = $this->request->post('openid');
        $mobile = $this->request->post('mobile');

        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register1($mobile, $mobile, $openid, []);
        }
        if ($ret) {
            $userInfo = $this->auth->getUserinfo();

            // 注册聊天账号
            $registerIm = $this->registerIm($userInfo['im'], $userInfo['nickname'], $userInfo['avatar']);
            // var_dump($registerIm);exit;
            if ($registerIm['ActionStatus'] != "OK") {
                $this->error('聊天账号注册失败');
            }

            switch ($userInfo['type']) {
                case 0:
                    if ($userInfo['is_vip'] == 1 && $userInfo['expire_time'] > time()) {
                        if ($userInfo['expire_time'] > 0) {
                            $userInfo['expire_time'] = ceil(($userInfo['expire_time'] - time()) / 86400);
                        }
                    } else {
                        $userInfo['expire_time'] = 0;
                        $userInfo['is_vip'] = 0;
                    }
                    $userInfo['collection_num'] = db('collection')->where('user_id', $userInfo['id'])->count();
                    $userInfo['goutong'] = db('order')->where(['user_id' => $userInfo['id'], 'type' => 3, 'is_pay' => 1])->count();
                    break;
                case 1:
                    $info = db('lawyer_info')->field('introduction,name as nickname,avatar')->where('user_id', $userInfo['id'])->where('status', '1')->find();
                    $userInfo = array_merge($userInfo, $info);
                    break;
//                case 2:
//                    $info = db('partner')->field('name as nickname,avatar')->where('user_id', $userInfo['id'])->find();
//                    $userInfo = array_merge($userInfo, $info);
//                    break;
                case 3:
                    $info = db('company_info')->field('name as nickname,avatar')->where('user_id', $userInfo['id'])->where('status', '1')->find();
                    $userInfo = array_merge($userInfo, $info);
                    break;
            }

            if (strpos($userInfo['avatar'], 'https://wx.qlogo.cn/') === false) {
                $userInfo['avatar'] = imgUrl($userInfo['avatar']);
            }

            // 已提现金额
            $withdraw = db('withdraw')->where('status', '3')->where('user_id', $userInfo['id'])->sum('money');
            $userInfo['withdraw_money'] = $withdraw;
            // 聊天密钥
            $userInfo['user_sig'] = $this->getUserSig($userInfo['im']);

            // 用户是否已关注公众号
//            if ($userInfo['mp_openid']) {
//                $userInfo['is_subscribe'] = $this->isSubscribe($userInfo['mp_openid']);
//            } else {
//                $userInfo['is_subscribe'] = 0;
//            }
//
//            if (!$userInfo['mp_openid']) {
//                $userInfo['mp_openid'] = "";
//            }

//            if (empty($userInfo['qrcode'])) {
            // $instance = new Qrcode();
            // $instance->invitation1($userInfo['id']);
//            }
            $this->success('登录成功', $userInfo);
        } else {
            $this->error($this->auth->getError());
        }
    }


    /**
     * 会员登录
     *
     * @param string $account 账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $code = $this->request->post('code');
        $openid = $this->request->post('openid');
        $avatar = $this->request->post('avatar');
        $nickname = $this->request->post('nickname');
        if (!$account || !$code || !$openid || !$avatar || !$nickname) {
            $this->error('缺少参数');
        }

        $ret = Sms::check($account, $code, 'register');
//        var_dump($ret);exit;
        if (!$ret) {
            $this->error('验证码不正确');
        }

        $ret = $this->auth->login($account, $code, $openid, $avatar, $nickname);
        if ($ret) {
            $userInfo = $this->auth->getUserinfo();
            switch ($userInfo['type']) {
                case 0:
                    if ($userInfo['expire_time'] > time() && $userInfo['is_vip'] == 1) {
                        if ($userInfo['expire_time'] > 0 && $userInfo['expire_time'] > time()) {
                            $userInfo['expire_time'] = ceil(($userInfo['expire_time'] - time()) / 86400);
                        }
                    } else {
                        $userInfo['expire_time'] = 0;
                        $userInfo['is_vip'] = 0;
                    }

                    $userInfo['collection_num'] = db('collection')->where('user_id', $userInfo['id'])->count();
                    $userInfo['goutong'] = db('order')->where(['user_id' => $userInfo['id'], 'type' => 3, 'is_pay' => 1])->count();
                    break;
                case 1:
                    $info = db('lawyer_info')->field('introduction,name as nickname,avatar')->where('user_id', $userInfo['id'])->where('status', '1')->find();
                    $userInfo = array_merge($userInfo, $info);
                    break;
//                case 2:
//                    $info = db('partner')->field('name as nickname,avatar')->where('user_id', $userInfo['id'])->find();
//                    $userInfo = array_merge($userInfo, $info);
//                    break;
                case 3:
                    $info = db('company_info')->field('name as nickname,avatar')->where('user_id', $userInfo['id'])->where('status', '1')->find();
                    $userInfo = array_merge($userInfo, $info);
                    break;
            }

            if (strpos($userInfo['avatar'], 'https://') === false) {
                $userInfo['avatar'] = imgUrl($userInfo['avatar']);
            }

            // 已提现金额
            $withdraw = db('withdraw')->where('status', '3')->where('user_id', $userInfo['id'])->sum('money');
            $userInfo['withdraw_money'] = $withdraw;
            // 聊天密钥
            $userInfo['user_sig'] = $this->getUserSig($userInfo['im']);

            // 用户是否已关注公众号
            if ($userInfo['mp_openid']) {
                $userInfo['is_subscribe'] = $this->isSubscribe($userInfo['mp_openid']);
            } else {
                $userInfo['is_subscribe'] = 0;
            }

            if (!$userInfo['mp_openid']) {
                $userInfo['mp_openid'] = "";
            }

            $im = db('user')->where('id', $this->auth->id)->value('im');
            $this->updateImUserInfo($im, $userInfo['nickname'], $userInfo['avatar']);

            $this->success(__('Logged in successful'), $userInfo);
        } else {
            $this->error($this->auth->getError());
        }
    }


    /**
     * 生成用户聊天密钥
     *
     * @param string $im 聊天账号
     * @return string
     */
    public function getUserSig($im)
    {
        $sig = new TLSSigAPIv2();
        return $sig->genSig($im);
    }


    /**
     * 注册聊天账号
     *
     * @param string $username 账号
     * @param string $nickname 昵称
     * @param string $avatar 头像
     * @return array
     */
    public function registerIm($username, $nickname, $avatar)
    {
        $userInfo = array(
            'UserID' => $username,
            'Nick' => $username,
            'FaceUrl' => 'https://lvshi.phpcaff.cn/assets/img/avatar.png',
            // 'Type' => 0
        );

        $data = json_encode($userInfo);

        $sdkappid = config('site.sdkappid');
        // 生成用户聊天账号密钥
        $userSig = $this->getUserSig('administrator');
        $url = "https://console.tim.qq.com/v4/im_open_login_svc/account_import?usersig=$userSig&identifier=administrator&sdkappid={$sdkappid}&contenttype=json";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: text'));
        $result = curl_exec($ch);
        curl_close($ch);
        return json_decode($result, true);
    }


    /**
     * 判断用户是否已关注公众号
     * @param string $openid 用户openid
     */
    public function isSubscribe($openid)
    {
        $token = Message::getMpAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$token&openid=$openid&lang=zh_CN";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: text'));
        $result = curl_exec($ch);
        curl_close($ch);

        $resultData = json_decode($result, true);

        if (isset($resultData['subscribe']) && $resultData['subscribe'] == 1) {
            return $resultData['subscribe'];
        } else {
            return 0;
        }
    }
}